package org.jeecg.modules.innerApi.bwgfApi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baiwang.bop.client.BopException;
import com.baiwang.bop.client.IBopClient;
import com.baiwang.bop.client.ILoginClient;
import com.baiwang.bop.client.impl.BopRestClient;
import com.baiwang.bop.client.impl.PostLogin;
import com.baiwang.bop.request.impl.LoginRequest;
import com.baiwang.bop.request.impl.bizinfo.CompanySearchRequest;
import com.baiwang.bop.request.impl.bizinfo.SearchRequest;
import com.baiwang.bop.respose.entity.LoginResponse;
import com.baiwang.bop.respose.entity.bizinfo.CompanySearchResponse;
import com.baiwang.bop.respose.entity.bizinfo.SearchResponse;
import com.baiwang.open.client.BWRestClient;
import com.baiwang.open.client.IBWClient;
import com.baiwang.open.entity.request.OutputInvoiceIssueRequest;
import com.baiwang.open.entity.response.OutputInvoiceIssueResponse;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.innerApi.bwgfApi.convert.BwRequestParamConvert;
import org.jeecg.modules.innerApi.bwgfApi.service.IBaiWangSkfpService;
import org.jeecg.modules.innerApi.common.requestDto.InvoiceParam;
import org.jeecg.modules.innerApi.common.responseDto.InvoiceRtn;
import org.jeecg.modules.innerApi.common.responseDto.ZnfmRtn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BaiWangSkfpServiceImpl implements IBaiWangSkfpService {
    private final static Logger log = LoggerFactory.getLogger(BaiWangSkfpServiceImpl.class);

    private static final String baiwangapi_url ="https://openapi.baiwang.com/router/rest";//百旺智能赋码、云抬头参数--url
    private static final String baiwangapi_appKey ="10000612";//百旺智能赋码、云抬头参数--appkey
    private static final String baiwangapi_appSecret ="e66ac4dc-3565-4757-be30-e3f6f14ce81f";//百旺智能赋码、云抬头参数--appSecret
    private static final String baiwangapi_userName ="admin_3000000002101";//百旺智能赋码、云抬头参数--userName
    private static final String baiwangapi_passWord ="123456";//百旺智能赋码、云抬头参数--passWord
    private static final String baiwangapi_UserSalt ="c3ad26b44144436885a1891096926298";//百旺智能赋码、云抬头参数--UserSalt


    /**
     * 获取token
     * @return
     * @throws Exception
     */
    private String getToken() throws RuntimeException {
        log.info("begin 登陆----------");
        ILoginClient loginClient = new PostLogin(baiwangapi_url);
        LoginRequest loginRequest = new LoginRequest();
        LoginResponse loginResponse = null;
        try {
            loginRequest.setAppkey(baiwangapi_appKey);
            loginRequest.setAppSecret(baiwangapi_appSecret);
            loginRequest.setUserName(baiwangapi_userName);
            loginRequest.setPasswordMd5(baiwangapi_passWord);
            loginRequest.setUserSalt(baiwangapi_UserSalt);
            loginResponse = loginClient.login(loginRequest);
            log.info(loginResponse.getExpires_in() + "");
            log.info(loginResponse.getToken_type() + "");
            log.info(loginResponse.getScope() + "");
            log.info(loginResponse.getRefresh_token() + "");
            log.info(loginResponse.getAccess_token() + "");

            return loginResponse.getAccess_token();
        } catch (BopException e) {
            log.error("登录失败!");
            log.error(e.getErrCode());
            log.error(e.getErrMsg());
            log.error(e.getMessage());
            throw new RuntimeException("获取token失败！" + e.getMessage() + e.getErrMsg());
        }
    }
    @Override
    public Result<JSONArray> getComSearch(String searchName) {
        JSONArray resAry=null,rtnAry=null;
        String error=null;
        try {
            //设置请求参数
            CompanySearchRequest request = new CompanySearchRequest();
            request.setCompanyName(searchName);//检索公司名称
            //获取token
            String token = this.getToken();
            IBopClient client = new BopRestClient(baiwangapi_url, baiwangapi_appKey, baiwangapi_appSecret);
            CompanySearchResponse response = client.execute(request, token, CompanySearchResponse.class);
            resAry = JSON.parseArray(JSON.toJSONString(response.getResult()));
            rtnAry = new JSONArray();
            for (int i = 0; i < resAry.size(); i++) {
                JSONObject jsjg = resAry.getJSONObject(i);
                JSONObject rtnjsjg = new JSONObject();
                rtnjsjg.put("nsrmc", jsjg.getString("name"));//公司名称
                rtnjsjg.put("nsrsbh", jsjg.getString("taxId"));//税号
                rtnjsjg.put("bank", jsjg.getString("bank"));//	开户银行
                rtnjsjg.put("bankAccount", jsjg.getString("bankAccount"));//	开户账号
                rtnjsjg.put("address", jsjg.getString("location"));//企业地址
                rtnjsjg.put("mobilePhone", jsjg.getString("mobilePhone"));//联系电话
                rtnAry.add(rtnjsjg);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            error="云抬头检索失败！" + e.getMessage();
        }
        if(StringUtils.isNotEmpty(error)){
           return Result.error(error);
        }else{
            return Result.OK("云抬头检索成功",rtnAry);
        }
    }

    @Override
    public Result<List<ZnfmRtn>> getZnfm(String spmc) {
        JSONArray resAry=null;
        String msg=null;
        List<ZnfmRtn> rtnList = null;
        try {
            //设置请求参数
            SearchRequest request = new SearchRequest();
            request.setCommodityName(spmc);//商品名称
            //获取token
            String token = this.getToken();
            IBopClient client = new BopRestClient(baiwangapi_url, baiwangapi_appKey, baiwangapi_appSecret);
            SearchResponse response = (SearchResponse) client.execute(request, token, SearchResponse.class);
            if(response.success) {
                resAry = JSON.parseArray(JSON.toJSONString(response.getRecommendations()));
                if (resAry != null) {
                    rtnList = new ArrayList<>();
                    for (int i = 0; i < resAry.size(); i++) {
                        JSONObject fmjg = resAry.getJSONObject(i);
                        ZnfmRtn rtnfmjg = new ZnfmRtn();
                        rtnfmjg.setPercent(fmjg.getString("prob"));//匹配率
                        rtnfmjg.setSpmc(fmjg.getString("parentName"));//商品名称
                        rtnfmjg.setCode(fmjg.getString("code"));//税收分类编码
                        rtnfmjg.setSsflmc(fmjg.getString("shortName"));//税收分类名称
                        rtnfmjg.setDesc(fmjg.getString("desc"));//描述

                        rtnList.add(rtnfmjg);
                    }
                }
            }else{
                msg=response.getMessage();
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        if(StringUtils.isNotEmpty(msg)){
            return Result.error(msg);
        }else{
            return  Result.OK("赋码成功",rtnList);
        }
    }

    /**
     * 发票开具
     * @param dkdjParam
     * @return
     */
    @Override
    public InvoiceRtn invoice(InvoiceParam dkdjParam) {
        String token = this.getToken();

        OutputInvoiceIssueRequest request = BwRequestParamConvert.invoiceParamConvert(dkdjParam);


        IBWClient client = new BWRestClient(baiwangapi_url, baiwangapi_appKey, baiwangapi_appSecret); // 初始化一个客户端
        OutputInvoiceIssueResponse response = client.outputInvoice().issue(request, token);
        log.info("请求ID：" + response.getRequestId());
        log.info("success：" + response.getSuccess());

        return BwRequestParamConvert.invoiceReturnConvert(response);
    }
}
